<?php

class C_UploadController extends Controller {
 
    // 首页方法
    function index() {
		exit('upload_index');
    }
	
	/**
	 * iframe 插件 $_FILE上传
	 */
	function iframeupload(){
        header("Content-type: text/html; charset=utf-8");
        $size = isset($GLOBALS['ADMIN']['update_size']) ? $GLOBALS['ADMIN']['update_size']*1024 : 1024*1024*10;
        $type = isset($GLOBALS['ADMIN']['update_type']) ? $GLOBALS['ADMIN']['update_type'] : '';
        $cut_c = isset($_POST['cut_c']) && intval($_POST['cut_c']) ? intval($_POST['cut_c']) : 1;
        $subFileCount = isset($_FILES['filename']['name']) ? count($_FILES['filename']['name']) : 1;
        // 错误提示
        echo '<script>'.PHP_EOL;
        echo 'function zhl_file_hide(){'.PHP_EOL;
        echo 'window.parent.document.getElementById("zhl_file_msg").innerText = "";'.PHP_EOL;
        echo 'var zhl_file_masks = window.parent.document.getElementById("zhl_file_masks");'.PHP_EOL;
        echo 'zhl_file_masks.parentNode.removeChild(zhl_file_masks);'.PHP_EOL;
        echo 'var zhl_file_box = window.parent.document.getElementById("zhl_file_box");'.PHP_EOL;
        echo 'zhl_file_box.parentNode.removeChild(zhl_file_box);}'.PHP_EOL;
        echo '</script>'.PHP_EOL;

        // 判断个数限制
        if($subFileCount > $cut_c || !isset($_POST) || empty($_POST)){
            $msg = '出错了请重试';
            if($subFileCount > $cut_c){
                $msg = "不能大于$cut_c".'个';
            }
            echo '<script>'.PHP_EOL;
            echo 'window.parent.document.getElementById("zhl_file_msg").innerText = "'.$msg.'";'.PHP_EOL;
            //echo 'layer.msg("'.$msg.'")'.PHP_EOL;
            echo 'setTimeout("zhl_file_hide()","2000");'.PHP_EOL;
            echo '</script>'.PHP_EOL;
            exit;
        }
        // 开始文件上传
        $array = array(
            'input' => 'filename',
            'path' => './'.SYS_PATH_FILE.'uploads/'.date("Ym").'/',
            'size' => $size,
            'type' => $type,
            'thum_flag' => 0,
        );
        $up = new UploadsFiles();
        $res = $up->uploadFile($array);
        // 上传失败提示
        if(empty($res)){
            echo '<script>'.PHP_EOL;
            //echo 'layer.msg("上传失败！")'.PHP_EOL;
            echo 'window.parent.document.getElementById("zhl_file_msg").innerText = "上传失败";'.PHP_EOL;
            echo 'setTimeout("zhl_file_hide()","2000");'.PHP_EOL;
            echo '</script>'.PHP_EOL;
            exit;
        }
        // 统计失败个数
        $msg = '';
        $fail = 0;
        $filePath = array();
        foreach($res as $k=>$v){
            if(!isset($v['code']) || $v['code'] != 10000){
                $fail ++;
                $msg .= $fail.'个上传失败';
            }else{
                $filePathName = isset($v['data']['path']) ? str_replace("./","", $v['data']['path']) : '';
                $filePath[] = $filePathName ? str_replace("public/","", $v['data']['path']) : '';
            }
        }
        echo '<script>'.PHP_EOL;
        $msg = $msg ? $msg : '上传成功';
        echo 'window.parent.document.getElementById("zhl_file_msg").innerText = "'.$msg.'";'.PHP_EOL;
        //echo 'layer.msg("'.$msg.'")'.PHP_EOL;
        echo 'setTimeout("zhl_file_hide()","2000");'.PHP_EOL;
        echo '</script>'.PHP_EOL;

        // 处理文件路径
        $filePath = array_filter($filePath);
        if(!empty($filePath)){
            $filePathStr = implode('|', $filePath);
            $selected = isset($_POST['selected']) ? $_POST['selected'] : '';
            $selectval = isset($_POST['selectval']) ? intval($_POST['selectval']) : '';
            // 添加文件日志
            $commonSer = new C_CommonServe();foreach($filePath as $v){$commonSer->addFileLog($v);}
            echo '<script>'.PHP_EOL;
            echo 'function getElementsClass(classnames) {
                    var classobj = new Array();
                    var classint = 0;
                    var tags = window.parent.document.getElementsByTagName("*"); 
                    for (var i in tags) {
                        if (tags[i].nodeType == 1) {
                            if (tags[i].getAttribute("class") == classnames){
                                classobj[classint] = tags[i];
                                classint++;
                            }
                        }
                    }
                    return classobj; 
                }'.PHP_EOL;
            echo 'getElementsClass("'.$selected.'")['.$selectval.'].value = "'.$filePathStr.'";'.PHP_EOL;
            //echo 'getElementsClass("dowload_input_btn")['.$selectval.'].href = "'.SYS_HOST.$filePathStr.'";'.PHP_EOL;
            echo 'setTimeout("zhl_file_hide()","2000");'.PHP_EOL;
            echo '</script>'.PHP_EOL;
        }
        exit;
    }

    /**
     * Notes: wangEeitor编辑器 图片上传
     * User: ZhuHaili
     * Date: 2020/11/13
     */
	function fileupload(){
        $size = isset($GLOBALS['ADMIN']['update_pic_size']) ? $GLOBALS['ADMIN']['update_pic_size']*1024 : 1024*1024*2;
        $type = isset($GLOBALS['ADMIN']['update_pic_type']) ? $GLOBALS['ADMIN']['update_pic_type'] : 'pjpeg|jpeg|jpg|gif|bmp|png';
		$array = array(
			'input' => 'file',
			'type' => $type,
			'size' => $size,
			'path' => './'.SYS_PATH_FILE.'uploads/'.date("Ym").'/',
		);
        $array['thum_flag'] = 6; // 不超过设定按原图超过按照设定
        $array['thum_width'] = 1000;            // 缩略图设定最大宽
        $array['thum_height'] = 1000;           // 缩略图设定最大高
        $array['thum_quality'] = 100;           // 缩略图质量
        $array['thum_path'] = $array['path'];

        $up = new UploadsFiles();
        $res = $up->uploadFile($array);
        if(isset($res['code']) && $res['code'] == 10000){
            $fileUrl = str_replace("./", "", $res['data']['thum_path']);
            $fileUrl = $fileUrl ? str_replace("public/", "", $fileUrl) : '';
            $fileUrl = SYS_LINK.$fileUrl;
            $commonSer = new C_CommonServe();
            $commonSer->addFileLog($fileUrl);
            echo $fileUrl;
        }else{
            die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "移动上传文件失败。"}, "id" : "id"}');
        }
	}
	
	/**
	 * base64上传
	 */
	function base64upload(){
		$data = isset($_POST['base64Data']) ? $_POST['base64Data'] : '';
		$size = isset($GLOBALS['ADMIN']['update_pic_size']) ? $GLOBALS['ADMIN']['update_pic_size']*1024 : 1024*1024*2;
		$type = isset($GLOBALS['ADMIN']['update_pic_type']) ? $GLOBALS['ADMIN']['update_pic_type'] : 'pjpeg|jpeg|jpg|gif|bmp|png';
        $cut_w = isset($_GET['cut_w']) && intval($_GET['cut_w']) ? intval($_GET['cut_w']) : 0; // 裁剪宽
        $cut_h = isset($_GET['cut_h']) && intval($_GET['cut_h']) ? intval($_GET['cut_h']) : 0; // 裁剪高
        $cut_c = isset($_GET['cut_c']) && intval($_GET['cut_c']) ? intval($_GET['cut_c']) : 1; // 图片上传个数控制
        $cut_f = isset($_GET['cut_f']) && intval($_GET['cut_f']) ? intval($_GET['cut_f']) : 0; // 裁剪类型
        $cut_t = isset($_GET['cut_t']) && intval($_GET['cut_t']) ? intval($_GET['cut_t']) : 0; // 有值则保存原图
        $other = isset($_GET['other']) && $_GET['other'] ? $_GET['other']: '';
        if(count($data) > $cut_c){
            $result = array('code'=>40000, 'msg'=>"不能大于$cut_c".'个', 'data'=>array());
            if(!isset($res[0])){
                Fun::json($result, true);
            }
        }
		$arr = array(
			'base64' => $data,
			'type' => $type,
			'size' => $size,
			'path' => './'.SYS_PATH_FILE.'uploads/'.date("Ym").'/'
		);

        if($cut_f){
            $arr['thum_flag'] = $cut_f;
            $arr['thum_width'] = $cut_w;            // 缩略图宽
            $arr['thum_height'] = $cut_h;           // 缩略图高
            $arr['thum_quality'] = 100;             // 缩略图质量
            $arr['thum_path'] = $cut_t ? $arr['path'].'thum/' : $arr['path'];
        }

        $up = new UploadsFiles();
        $res = $up->uploadFile($arr);
        $commonSer = new C_CommonServe();
        /*$result = array('code'=>30000, 'msg'=>'上传失败', 'data'=>array());
        if(!isset($res[0])){
            Fun::json($result, true);
        }*/
        //$result = array('code'=>10000, 'msg'=>'success', 'data'=>array());
        $filePaths = array();
        foreach($res as $k=>$v){
            $res[$k] = $v;
            $res[$k]['imgurl'] = $v['data']['path'];
            if(isset($v['data']['thum_path']) && $v['data']['thum_path']){
                //@unlink($res[$k]['imgurl']); //
                $res[$k]['imgurl'] = $v['data']['thum_path'];
            }
            if($res[$k]['imgurl']){
                $imgurl = str_replace("./","", $res[$k]['imgurl']);
                $res[$k]['imgurl'] = $imgurl ? str_replace("public/", "", $imgurl) : '';
                $commonSer->addFileLog($res[$k]['imgurl']);
            }
            $filePaths[] = $res[$k]['imgurl'];
            // 其他规则
            if(isset($v['code']) && $v['code'] == 10000 && $other && $cut_f){
                $otherRules = explode('|', $other);
                foreach($otherRules as $r){
                    $rule = explode('=', $r);
                    $w = isset($rule[0]) ? $rule[0] : 0;
                    $h = isset($rule[1]) ? $rule[1] : 0;
                    //$params['local'] = $result['data']['path'];
                    $params2['local'] = $v['data']['path']; //【必填】为本地图片路径时
                    $params2['thum_keep'] = 1;              // 保持原名字一致
                    $params2['thum_flag'] = $cut_f;         // 1:原图压缩到指定宽高，2:宽度固定高度自适应，3:高度固定宽度自适应，4:以原图中心点截图,5智能裁剪
                    $params2['thum_path'] = $arr['path'].'thum'.$w.'x'.$h.'/';
                    $params2['thum_width'] = $w;            // 缩略图宽
                    $params2['thum_height'] = $h;           // 缩略图高
                    $req = $up->createThum($params2);
                    if(isset($req['data']['thum_path']) && $req['data']['thum_path']){
                        $filePaths[] = $req['data']['thum_path'];
                    }
                }
            }
        }
        // $filePaths所有文件路径可后续上传oss等处理
        // 其他上传云端代码
        //register_shutdown_function(array($this, 'uploadOther'), $filePaths); // 异步处理
        $request = $this->uploadOther($filePaths); // 同步处理
        //
        /*$res
[0] => Array
        (
            [code] => 10000
            [msg] => 文件上传成功
            [data] => Array
                (
                    [width] => 911
                    [height] => 726
                    [size] => 84202
                    [sizetxt] => 82.23kb
                    [path] => ./uploads/202211/20221108111436582386.jpeg
                    [type] => jpeg
                )
            [imgurl] => uploads/202211/20221108111436582386.jpeg
        )
        */

        Fun::json($res, true);
	}

    /**
     * Notes:图片手动选择裁剪文件上传
     * User: ZhuHaili
     * Date: 2022/9/11
     */
	public function base64cut(){
        $data = isset($_POST['base64Data']) ? $_POST['base64Data'] : '';
        $size = isset($GLOBALS['ADMIN']['update_pic_size']) ? $GLOBALS['ADMIN']['update_pic_size']*1024 : 1024*1024*2;
        $type = isset($GLOBALS['ADMIN']['update_pic_type']) ? $GLOBALS['ADMIN']['update_pic_type'] : 'pjpeg|jpeg|jpg|gif|bmp|png';
        $arr = array(
            'base64' => $data,
            'type' => $type,
            'size' => $size,
            'path' => './'.SYS_PATH_FILE.'uploads/'.date("Ym").'/'
        );
        $up = new UploadsFiles();
        $res = $up->uploadFile($arr);
        $result = array('code'=>30000, 'msg'=>'上传失败', 'data'=>array());
        if(!isset($res['code']) || $res['code'] != 10000){
            Fun::json($result, true);
        }
        $pathFile = '';
        if(isset($res['data']['path']) && $res['data']['path']){
            $pathFile = str_replace('./', '', $res['data']['path']);
        }
        $result['code'] = 10000;
        $result['msg'] = '图片上传成功';
        $result['data']['imgurl'] = $pathFile;
        if($pathFile){
            $commonSer = new C_CommonServe();
            $commonSer->addFileLog($pathFile);
        }
        Fun::json($result, true);
    }

    /**
     * Notes:图片上传云端
     * User: ZhuHaili
     * Date: 2022/11/8
     */
    public function uploadOther($filePaths){
        if(empty($filePaths)){
            return false;
        }

    }
}